package com.aqie.appletserver.service.impl;

import com.aqie.appletserver.bean.BaiduToken;
import com.aqie.appletserver.bean.response.TokenResponse;
import com.aqie.appletserver.repository.BaiduTokenRepository;
import com.aqie.appletserver.service.IBaiduTokenService;
import com.aqie.appletserver.utils.RequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class BaiduTokenService implements IBaiduTokenService {

    @Value("${baidu.tokenUrl}")
    private String AUTH_TOKEN ;

    @Value("${baidu.apiKey}")
    private String API_KEY ;

    @Value("${baidu.secretKey}")
    private String SECRET_KEY ;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private BaiduTokenRepository baiduTokenRepository;

    @Override
    public BaiduToken save(BaiduToken token) {
        return baiduTokenRepository.save(token);
    }

    @Override
    public BaiduToken getByApikeyAndType(String apiKey, String type) {
        return baiduTokenRepository.getByApiKeyAndType(apiKey, type);
    }

    @Override
    public TokenResponse getAuthToken() {
        String type = "voice";
        // 1. 查询本地accessToken
        BaiduToken tokenDatabase = this.getByApikeyAndType(API_KEY, type);
        TokenResponse response = new TokenResponse();
        if(tokenDatabase == null){
            // 3. 构造请求参数
            response = getTokenFromNet();
            log.info("数据库不存在 response:{}", response);
            if(response != null){
                saveTokeToDatabase(type, response);
            }
        } else {
            // 2.判断是否过期
            boolean expired = ((tokenDatabase.getCreateTime() + tokenDatabase.getExpireTime()) < (int)(System.currentTimeMillis() / 1000));
            log.info("{}, {}", tokenDatabase.getCreateTime() + tokenDatabase.getExpireTime(), (int)(System.currentTimeMillis() / 1000));
            if(expired){
                response = getTokenFromNet();
                log.info("过期 重新请求 response:{}", response);
                if(response != null){
                    updateTokeToDatabase(type, response,tokenDatabase.getId());
                }
            }else {
                response.setAccessToken(tokenDatabase.getAccessToken());
                response.setExpiresIn(tokenDatabase.getExpireTime());
            }
        }

        return response;
    }

    private void saveTokeToDatabase(String type, TokenResponse response) {
        BaiduToken token = new BaiduToken();
        token.setAccessToken(response.getAccessToken());
        token.setExpireTime(response.getExpiresIn());
        token.setApiKey(API_KEY);
        token.setType(type);
        token.setCreateTime((int)(System.currentTimeMillis() / 1000));
        // 保存本地数据库
        BaiduToken save = this.save(token);
    }

    private void updateTokeToDatabase( String type, TokenResponse response, int id) {
        BaiduToken token = new BaiduToken();
        token.setAccessToken(response.getAccessToken());
        token.setExpireTime(response.getExpiresIn());
        token.setApiKey(API_KEY);
        token.setType(type);
        token.setId(id);
        token.setCreateTime((int)(System.currentTimeMillis() / 1000));
        // 保存本地数据库
        BaiduToken save = this.save(token);
    }

    private TokenResponse getTokenFromNet() {
        TokenResponse response;
        Map<String, String> requestMap = new HashMap<>();
        requestMap.put("grant_type", "client_credentials");
        requestMap.put("client_id", API_KEY);
        requestMap.put("client_secret", SECRET_KEY);
        String rqstUrl = RequestUtils.getRqstUrl(AUTH_TOKEN, requestMap);
        //log.info("{}", rqstUrl);
        // 4. 请求 accessToken
        response = this.restTemplate.getForObject(rqstUrl, TokenResponse.class);

        return response;
    }

}
